from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)


# @app.route('/')
# def hello_world():  # put application's code here
#     return 'Hello World!'
@app.route('/add/user', methods=['POST', 'GET'])
def add_user():
    if request.method == "GET":
        return render_template("add_user.html")
    else:
        data = request.form
        username = data.get('username')
        password = data.get('password')
        mobile = data.get('mobile')
        # info = "您的用户名：{}，密码：{}，手机号：{}".format(username,password,mobile)
        # print(info)

        # 存入数据库
        if data and username and password:
            # 链接MySQL
            conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="", charset='utf8', db='unicom')
            cursor = conn.cursor()

            # 千万不要用字符串格式化做SQL语句拼接，有安全隐患SQL注入：可以这样
            sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
            cursor.execute(sql, [username, password, mobile])
            conn.commit()

            # 关闭连接
            cursor.close()
            conn.close()
            return "用户信息输入成功"

        return "请检查输入个数"


@app.route('/show/users', methods=['POST', 'GET'])
def show_users():
    if request.method == 'GET':
        return render_template('show_users.html')
    else:
        # 链接MySQL
        conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="", charset='utf8', db='unicom')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 飘黄没事照样用

        # 还可以：
        sql = "select * from admin"
        cursor.execute(sql)
        data_list = cursor.fetchall()

        # info = ''
        # info += "{:<2}\t{:<15}{:<20}{:<11}<br>".format("id", "username", "password", "mobile")
        # for i in data_list:
        #     info += "{:<2}\t{:<15}{:<20}{:<11}<br>".format(i["id"], i["username"], i["password"], i["mobile"], )

        # print(data_lt)

        # 关闭连接
        cursor.close()
        conn.close()
        return render_template("show_users.html",data_list=data_list)


if __name__ == '__main__':
    app.run()
